package com.android.calldelay.receiver;



import java.util.Calendar;

import com.android.calldelay.AppInfo;
import com.android.calldelay.CallDelayedAppWidgetProvider;
import com.android.calldelay.R;
import com.android.calldelay.services.ServiceForCallingStateRecever;


import android.R.integer;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.ContentObserver;
import android.database.Cursor;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Handler;
import android.provider.CallLog;
import android.telephony.PhoneStateListener;
import android.telephony.SmsManager;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.RemoteViews;
import android.widget.Toast;

public class CallingStateReceiver extends BroadcastReceiver {
	private static final String LOG_TAG = "CallingStateReceiver";

	public static final long DAY_IN_MILISECONDS = 0;
	public static final String TAG = "Call_Receiver";
	private Context ctx;
	public long duration;
	public boolean wasRinging;
	private boolean FLAG_DISCONNECTED = false;
	private Intent serviceIntent;
	private long end_time;
	private long start_time;

	@Override
	public void onReceive(Context context, Intent intent) {
		ctx = context;



		String action = intent.getAction();
		/*if(action.equalsIgnoreCase("android.intent.action.PHONE_STATE")){
			if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
					TelephonyManager.EXTRA_STATE_RINGING)) {

				start_time=System.currentTimeMillis();

			}         
			if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
					TelephonyManager.EXTRA_STATE_IDLE)) {
				end_time=System.currentTimeMillis();
				//Total time talked =
						long total_time = end_time-start_time;
						Toast.makeText(context, "tatal talked time is"+total_time, Toast.LENGTH_SHORT).show();
						//Store total_time somewhere or pass it to an Activity using intent

			}    

		}   */


		IncomingCallListener phoneListener = new IncomingCallListener();
		TelephonyManager telephony = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);


		if (intent.getAction()
				.equals("android.intent.action.NEW_OUTGOING_CALL")) {

			//Log.i("", " :::::::::::: inside onReceive if &&&&&&  :::::::::::::");
			AppInfo.DIAL_ATTEMPTS --;
			telephony.listen(phoneListener,
					PhoneStateListener.LISTEN_CALL_STATE);

			Log.d(LOG_TAG, "dial attempts "+AppInfo.DIAL_ATTEMPTS);


		}
	}

	class IncomingCallListener extends PhoneStateListener {

		public boolean isOffHook;
		//private CallLogObserver observer;
		private Intent serviceIntent;
		private boolean disconnected;
		private int value;

		@Override
		public void onCallStateChanged(int state, String incomingNumber) {
			switch (state) {
			case TelephonyManager.CALL_STATE_RINGING:
				wasRinging = true;
				break;
			case TelephonyManager.CALL_STATE_OFFHOOK:
				isOffHook = true;
				setSpeaker();
				if (AppInfo.DIAL_ATTEMPTS>=0) {
					// starting the dervice for redialing 
					serviceIntent = new Intent(new Intent(ctx, ServiceForCallingStateRecever.class));
					ctx.startService(serviceIntent);

				}else {
					serviceIntent = new Intent(new Intent(ctx, ServiceForCallingStateRecever.class));
					ctx.stopService(serviceIntent);
				}

				if (AppInfo.DIAL_ATTEMPTS == 0) {
					updateWidget();

				}


				// registerContentObserver();
				if (!wasRinging) {
					// Start your new activity

				} else {
					// Cancel your old activity

				}

				disconnected = true;
				value = 1;


				break;

			case TelephonyManager.CALL_STATE_IDLE:
				wasRinging = true; 	
				if(disconnected){
					value = 2;
				}else{
					value = 0 ;
					disconnected = false;
				}



				break;
			}
			if (value == 2) {
				// Toast.makeText(ctx, "call is disconnected",Toast.LENGTH_SHORT).show();
				AppInfo.FLAG_CALL_IS_DISCONNECTED = true;
			}
		}



		private void updateWidget() {

			RemoteViews localRemoteViews = new RemoteViews(ctx.getPackageName(),R.layout.call_delayed_appwidget_layout);
			localRemoteViews.setViewVisibility(R.id.btn_widget_delayapp_start, View.VISIBLE);
			localRemoteViews.setViewVisibility(R.id.textView_title, View.GONE);
			ComponentName localComponentName = new ComponentName(ctx, CallDelayedAppWidgetProvider.class);
			AppWidgetManager.getInstance(ctx).updateAppWidget(localComponentName, localRemoteViews);

		}



		private void setSpeaker() {

			SharedPreferences setting = ctx.getSharedPreferences(
					AppInfo.APP_PREF, 0);
			boolean isSpeaker = setting.getBoolean(
					AppInfo.KEY_OPEN_SPEAKER_CHECKBOX, false);
			if (isSpeaker) {
				AudioManager audioManager = (AudioManager) ctx
						.getSystemService(Context.AUDIO_SERVICE);
				audioManager.setMode(AudioManager.MODE_IN_CALL); 
				audioManager.setSpeakerphoneOn(true);
				boolean isMaxSpeaker = setting.getBoolean(
						AppInfo.KEY_OPEN_SPEAKER_RB_MAX, false);
				if (isMaxSpeaker) {
					audioManager
					.setStreamVolume(
							AudioManager.STREAM_VOICE_CALL,
							audioManager
							.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL),
							0);
				} else {
					audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL, 1,
							0);
				}
			}



		}
	}

	/*public class CallLogObserver extends ContentObserver {

		private Context context;
		private boolean flag = true;


		public CallLogObserver(Handler handler, Context context) {
			super(handler);
			this.context = context;
		}
		@Override
		public boolean deliverSelfNotifications() {

			return true;
		}

		@Override
		public void onChange(boolean selfChange) {
			super.onChange(selfChange);
			Log.i(TAG, "CallLogs Onhange()");

			try {
				Cursor c = context.getContentResolver().query(
						CallLog.Calls.CONTENT_URI, null, null, null,
						CallLog.Calls.DATE + " DESC");
				if (c != null) {
					if (c.moveToFirst()) {
						int type = Integer.parseInt(c.getString(c
								.getColumnIndex(CallLog.Calls.TYPE)));

	 * increase call counter for outgoing call only

						if (type == 2) {
							String number = c.getString(c
									.getColumnIndex(CallLog.Calls.NUMBER));

							duration = c.getLong(c
									.getColumnIndex(CallLog.Calls.DURATION));

							Log.i(TAG, "numer = " + number + " type = " + type
									+ " duration = " + duration);

						}

						if (duration == 0 && wasRinging) {
							//AppInfo.REDIAL = true;

							AppInfo.CALL_DURATION = 0;
							redial();

							if (AppInfo.DIAL_ATTEMPTS>0) {

								Toast.makeText(ctx,
																"Your call is disconnected by receiver",
																Toast.LENGTH_LONG).show();

								if (AppInfo.DIAL_ATTEMPTS>=1) {
									if (AppInfo.DIAL_ATTEMPTS == 1 && AppInfo.FLAG) {
										dialFirstNumber();
									}else if(AppInfo.DIAL_ATTEMPTS == 2){
										dialSecondNumber();
										AppInfo.FLAG = false; 
									}
								}


								if (AppInfo.DIAL_ATTEMPTS % 2 != 0 && AppInfo.DIAL_ATTEMPTS >1) {
									dialFirstNumber();
									AppInfo.MESSAGE_COUNTER = 1;

								} else {
									dialSecondNumber();
									AppInfo.MESSAGE_COUNTER = 2;
								}
								 }else{
								// code for sending message
								Toast.makeText(context,"no more dial attempts",  Toast.LENGTH_SHORT).show();
								if (AppInfo.COUNT != 1) {
									if (AppInfo.MESSAGE_COUNTER == 1) {
										sendMessage("5556");
										AppInfo.COUNT = 1;
									}else {
										sendMessage("5558");
										AppInfo.COUNT = 1;
									}

								}

								  }


						} else {
							AppInfo.REDIAL = false;

							// code for sending text message
						}
					}
					c.close();
				} else
					Log.e(TAG, "Call Logs Cursor is Empty");
			} catch (Exception e) {

				Log.e("", "Error on onChange : " + e.toString());
			}
		}

		private void redial() {
			final int dialAttemptsFromPref = ctx.getSharedPreferences(AppInfo.APP_PREF, 0).getInt(AppInfo.KEY_DIAL_ATTEMPTS_KEY, 0);
			if (dialAttemptsFromPref == 0) {
				//send only message to first number
				//	Toast.makeText(ctx, "send only message to first number", Toast.LENGTH_SHORT).show();
				Log.i(TAG, "send only message to first number"+dialAttemptsFromPref);
				if (AppInfo.COUNT!=1) {
					//sendMessageToFirstNumber("5556");
					AppInfo.COUNT = 1;
				}

				//sendMessage("5556");
			} else {
				if (dialAttemptsFromPref <= 2) {



						if (AppInfo.FLAG ) {


						System.out.println("We are in AppInfo.FLAG condition "+AppInfo.FLAG);
						if (dialAttemptsFromPref == 1  ) {
							System.out.println("dialAttemptsFromPref == 1 "+AppInfo.FLAG);

							dialFirstNumber();
							AppInfo.COUNT = 0;
							//sendMessage("5556");
							AppInfo.FLAG = false;


						}else if (dialAttemptsFromPref == 2) {
							System.out.println("dialAttemptsFromPref == 2"+AppInfo.FLAG);
							dialSecondNumber();
							//sendMessage("5558");
							AppInfo.FLAG =false;
							AppInfo.COUNT = 0;

						}
					}else{ 
						if (AppInfo.COUNT!=1) {
							Toast.makeText(ctx, "Send the message", Toast.LENGTH_SHORT).show();
							System.out.println("We are in AppInfo.FLAG condition  "+AppInfo.FLAG);
							AppInfo.COUNT = 1;
						}

						//AppInfo.FLAG =true;
						//	AppInfo.COUNT = 0;

						//sendMessage("5556");



						// code for sending the message


					}




				}else{
					//Toast.makeText(ctx, "redialing is greater than 3", Toast.LENGTH_SHORT).show();


					// code for even and odd
					alternativeRedial();
				}

				//Toast.makeText(ctx, "alternetRedialingMesseging", Toast.LENGTH_SHORT).show();



				new Thread(){
				  public void run() {
					  alternativeRedial(dialAttemptsFromPref);
				  };

			 }.start();
				alternativeRedial(dialAttemptsFromPref);
			}

		}

		private void alternativeRedial(int dialAttemptsFromPref) {
			if (AppInfo.DIAL_ATTEMPTS >0) {
				if (dialAttemptsFromPref%2 == 0) {
					//Toast.makeText(context, ""+dialAttemptsFromPref,Toast.LENGTH_SHORT).show();
					if (AppInfo.DIAL_ATTEMPTS % 2 != 0) {
						dialSecondNumber();
						setUpAlarmForDisconnect();

						AppInfo.MESSAGE_COUNTER = 2;
						AppInfo.COUNT =0;


					} else    {

						dialFirstNumber();
						setUpAlarmForDisconnect();
						AppInfo.MESSAGE_COUNTER = 1;
						AppInfo.COUNT =0;

					}  

				}else {
					//Toast.makeText(context, ""+dialAttemptsFromPref,Toast.LENGTH_SHORT).show();
					if (AppInfo.DIAL_ATTEMPTS % 2 != 0) {
						//AppInfo.DIAL_ATTEMPTS--;
						dialFirstNumber();
						setUpAlarmForDisconnect();
						AppInfo.MESSAGE_COUNTER = 1;
						AppInfo.COUNT =0;


					} else{
						//AppInfo.DIAL_ATTEMPTS--;
						dialSecondNumber();
						setUpAlarmForDisconnect();
						AppInfo.MESSAGE_COUNTER = 2;
						AppInfo.COUNT = 0;

					}  

				}


			}else
			{ 

				// code for sending message
				//Toast.makeText(context,"no more dial attempts",  Toast.LENGTH_SHORT).show();
				if (AppInfo.COUNT != 1) {
					if (AppInfo.MESSAGE_COUNTER == 1) {

						//	sendMessageToFirstNumber("5556");
						AppInfo.COUNT = 1;
					}else if (AppInfo.MESSAGE_COUNTER == 2) {
						//sendMessageToSecondNumber("5558");
						AppInfo.COUNT = 1;


					} 

				}

			} 
		}




		private void setUpAlarmForDisconnect() {
					new Handler().postDelayed(new Runnable() {

			@Override
				public void run() {
					AlarmManager alarmManager = (AlarmManager)context. getSystemService(Context.ALARM_SERVICE);
					Intent intent = new Intent(context, OnCallDisconnectReceave.class);

					PendingIntent pendingIntent = PendingIntent
							.getBroadcast(context, 0, intent,
									PendingIntent.FLAG_UPDATE_CURRENT);

					// retriving the seconds 
					int secondsBeforeDialingAgain = context.getSharedPreferences(AppInfo.APP_PREF, 0)
							.getInt(AppInfo.KEY_SECONDS_BEFORE_DIALING_AGAIN,0);


					// Getting current time and add the seconds in it
					Calendar cal = Calendar.getInstance();
					cal.add(Calendar.SECOND, secondsBeforeDialingAgain);
					alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
							pendingIntent);

				}
			}, Toast.LENGTH_LONG);


			AlarmManager alarmManager = (AlarmManager)context. getSystemService(Context.ALARM_SERVICE);
			Intent intent = new Intent(context, OnCallDisconnectReceave.class);

			PendingIntent pendingIntent = PendingIntent
					.getBroadcast(context, 0, intent,
							PendingIntent.FLAG_UPDATE_CURRENT);

			// retriving the seconds 
			int secondsBeforeDialingAgain = context.getSharedPreferences(AppInfo.APP_PREF, 0)
					.getInt(AppInfo.KEY_SECONDS_BEFORE_DIALING_AGAIN,0);


			// Getting current time and add the seconds in it
			Calendar cal = Calendar.getInstance();
			cal.add(Calendar.SECOND, secondsBeforeDialingAgain);
			alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
					pendingIntent);

		}




		private void sendMessageToSecondNumber(String number) {
			String secondNumber = context.getSharedPreferences(AppInfo.APP_PREF, 0)
					.getString(AppInfo.KEY_SECOND_NUMBER_KEY, "N/A");
			String message = context.getSharedPreferences(AppInfo.APP_PREF, 0)
					.getString(AppInfo.KEY_MESSAGE_TEXT, "Message from Demo auto SmsManager");SmsManager sm = SmsManager.getDefault();
					sm.sendTextMessage(secondNumber, null, message, null, null);
		}

		private void sendMessageToFirstNumber(String number) {
			String firstNumber = context.getSharedPreferences(AppInfo.APP_PREF, 0)
					.getString(AppInfo.KEY_FIRST_NUMBER_KEY, "N/A");
			String message    = context.getSharedPreferences(AppInfo.APP_PREF, 0)
					.getString(AppInfo.KEY_MESSAGE_TEXT, "Message from Demo auto SmsManager");
			SmsManager sm = SmsManager.getDefault();

			sm.sendTextMessage(firstNumber, null, message, null, null);

		}

		private void sendMessage(String number) {
			SmsManager sm = SmsManager.getDefault();
			String firstNumber = context.getSharedPreferences(AppInfo.APP_PREF, 0)
					.getString(AppInfo.KEY_FIRST_NUMBER_KEY, "N/A");
			String message = context.getSharedPreferences(AppInfo.APP_PREF, 0)
					.getString(AppInfo.KEY_MESSAGE_TEXT, "Message from Demo auto SmsManager");
			sm.sendTextMessage(number, null, message, null, null);

		}

		private void dialFirstNumber() {
			   new Handler().postDelayed(new Runnable() {

				@Override
				public void run() {
					try{

						String firstNumber = context.getSharedPreferences(AppInfo.APP_PREF, 0)
								.getString(AppInfo.KEY_FIRST_NUMBER_KEY, "N/A");
						if (!firstNumber.equalsIgnoreCase("N/A")) {
							//String mobileNo = "5556";
							String uri = "tel:" + firstNumber.trim();
							Intent intent = new Intent(Intent.ACTION_CALL);
							intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
							intent.setData(Uri.parse(uri));

							ctx.startActivity(intent);



						}

						}catch (Exception e) {
							// TODO: handle exception


						}					
				}
			}, Toast.LENGTH_LONG);
			if (AppInfo.FLAG_CALL_IS_DISCONNECTED) {
				new Handler().postDelayed(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub

					}
				}, 0);

				try{

					String firstNumber = context.getSharedPreferences(AppInfo.APP_PREF, 0)
							.getString(AppInfo.KEY_FIRST_NUMBER_KEY, "N/A");
					if (!firstNumber.equalsIgnoreCase("N/A")) {
						//String mobileNo = "5556";
						String uri = "tel:" + firstNumber.trim();
						Intent intent = new Intent(Intent.ACTION_CALL);
						intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						intent.setData(Uri.parse(uri));

						ctx.startActivity(intent);
						AppInfo.FLAG_CALL_IS_DISCONNECTED =false;
						Log.d(LOG_TAG, "Call is disconnected "+AppInfo.FLAG_CALL_IS_DISCONNECTED);
						showToast("Call is connected"+AppInfo.FLAG_CALL_IS_DISCONNECTED);



					}

				}catch (Exception e) {
					// TODO: handle exception

				}
			}








		}
		private void dialSecondNumber() {


			if (AppInfo.FLAG_CALL_IS_DISCONNECTED) {
				new Handler().postDelayed(new Runnable() {

				@Override
				public void run() {
					try {
						String secondNumber = context.getSharedPreferences(
								AppInfo.APP_PREF, 0).getString(
								AppInfo.KEY_SECOND_NUMBER_KEY, "N/A");
						if (!secondNumber.equalsIgnoreCase("N/A")) {
							//String mobileNo = "5556";
							String uri = "tel:" + secondNumber.trim();
							Intent intent = new Intent(Intent.ACTION_CALL);
							intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
							intent.setData(Uri.parse(uri));
							ctx.startActivity(intent);
							AppInfo.FLAG_CALL_IS_DISCONNECTED = false;
							Log.d(LOG_TAG, "Call is disconnected "+AppInfo.FLAG_CALL_IS_DISCONNECTED);
							showToast("Call is connected"+AppInfo.FLAG_CALL_IS_DISCONNECTED);

						}
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				}
			}, 0);

				try {
					String secondNumber = context.getSharedPreferences(
							AppInfo.APP_PREF, 0).getString(
									AppInfo.KEY_SECOND_NUMBER_KEY, "N/A");
					if (!secondNumber.equalsIgnoreCase("N/A")) {
						//String mobileNo = "5556";
						String uri = "tel:" + secondNumber.trim();
						Intent intent = new Intent(Intent.ACTION_CALL);
						intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						intent.setData(Uri.parse(uri));
						ctx.startActivity(intent);
						AppInfo.FLAG_CALL_IS_DISCONNECTED = false;
						Log.d(LOG_TAG, "Call is disconnected "+AppInfo.FLAG_CALL_IS_DISCONNECTED);
						//showToast("Call is connected"+AppInfo.FLAG_CALL_IS_DISCONNECTED);

					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}




		}

		private void showToast(String msg) {
			Toast.makeText(context,msg, Toast.LENGTH_SHORT).show();

		}


	}
	 */



}